package com.health.trans.service.action;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSONObject;
import com.health.es.entity.data.MaterialApply;
import com.health.es.entity.log.TransformLog;
import com.health.es.temp.EsHelper;
import com.health.es.util.query.NativeSearchQuery;
import com.health.trans.service.CorrelationService;
import com.health.trans.util.EntityOperations;
import com.health.trans.util.ReflectKit;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermsQueryBuilder;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author nqlz
 */
public class AppendChildDataAction<T, J> extends TransAction<T, J> {


    protected AppendChildDataAction(Class<T> tClass, CorrelationService correlationService) {
        super(tClass, correlationService);
    }

    protected AppendChildDataAction(CorrelationService correlationService) {
        super(correlationService);
    }

    @Override
    public void transData(T t) {
        TransformLog transformLog = correlationService.correlation(t);
        if (null == transformLog) {
            //关联性校验通过
            appendChildrenData(t);
            memorySet.pushOther(tClass, t);
        } else {
            checkLog();
            //未关联到数据
            memorySet.pushLog(transformLog);
        }
    }

    public void appendChildrenData(T o) {
        String esKey = ReflectKit.getEsKeyByChildIdStr(o);
        TermsQueryBuilder source = QueryBuilders.termsQuery("source", esKey);
        List<TransformLog> transformLogList = EsHelper.search(TransformLog.class, source);
        if (CollUtil.isNotEmpty(transformLogList)) {
            for (TransformLog log : transformLogList) {
                String errorData = log.getErrorData();
                String tableName = log.getTableName();
                Class<Object> childClass = EntityOperations.getPojoClass(tableName);
                Object parseObject = JSONObject.parseObject(errorData, childClass);
                assert parseObject != null;
                memorySet.pushOther(childClass, parseObject);
            }
            //批量删除 elasticsearch 消费过的子表数据
            String[] ids = transformLogList.stream().map(i -> ReflectUtil.getFieldValue(i, "id").toString()).toArray(String[]::new);
            if (ArrayUtil.isNotEmpty(ids)){
                EsHelper.operations.delete(new NativeSearchQuery(QueryBuilders.idsQuery().addIds(ids)),tClass);
                EsHelper.operations.indexOps(tClass).refresh();
            }
        }
    }
}
